#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>


pid_t pid_child1, pid_child2;

void Parent_sighandler(int signum)
{
    static int count = 0;
    if (signum == SIGINT)
    {
        kill(pid_child1,SIGUSR1);//给子进程1 发送SIGUSR1信号
        kill(pid_child2,SIGUSR1);//给子进程2 发送SIGUSR1信号
    }
    else if (signum == SIGCHLD)
    {
        count ++;
        if (count == 2)
        {
            printf("Parent process exit!\n");
            exit(0);
        }
    }  
}

void child1_sighandler(int signum)
{
    printf("Child process 1 is killed by parent!\n");
    exit(0);//子进程退出后，发送SIGCHLD信号给父进程
}

void child2_sighandler(int signum)
{
    sleep(1);
    printf("Child process 2 is killed by parent!\n");
    exit(0);//子进程退出后，发送SIGCHLD信号给父进程
}

int main(int argc, char const *argv[])
{
    pid_t pid = fork(); //获取子进程1的进程号
    if (pid < 0)//错误
    {
        perror("fork");
        exit(-1);
    }
    else if (pid == 0)//子进程1
    {
        signal(SIGINT,SIG_IGN);
        signal(SIGUSR1,child1_sighandler);
        while (1)
        {
            sleep(1);
        }  
    }
    else //父进程
    {
        pid_child1 = pid;
        pid = fork(); 
        if (pid < 0)//错误
        {
            perror("fork");
            exit(-1);
        }
        else if (pid == 0) //子进程2
        {
            signal(SIGINT,SIG_IGN);
            signal(SIGUSR1,child2_sighandler);
            while (1)
            {
                sleep(1);
            }
        }
        else 
        {
            pid_child2 = pid;//获取子进程2的进程号
            signal(SIGINT,Parent_sighandler);

            //默认父进程对SIGCHLD是忽略的
            signal(SIGCHLD,Parent_sighandler);
            while (1)//父进程
            {
                sleep(1);
            }
        }
    }
    
    return 0;
}
